package com.are_you_learn.controller;

import com.are_you_learn.beans.Msg;
import com.are_you_learn.beans.Student;
import com.are_you_learn.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @author CONG
 * @date 2019-09-22 16:47
 **/

@Controller
@RequestMapping("/are_you_learn")
//@CrossOrigin

public class StudentController {

    @Autowired
    StudentService studentService;

    /**
     * 学生注册
     * @param
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/studentRegist",method = RequestMethod.POST)
    public Msg studentRegist(String realname,String username,String password,String email){

        Student student = new Student(null,realname,username,password,null,null,null,null,email,null);

        studentService.saveStudent(student);

        return Msg.success();
    }

    /**
     * 学生登陆
     * @param username,password
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/studentLogin",method = RequestMethod.POST)
    public Msg studentLogin(@RequestParam("username") String username, @RequestParam("password") String password,HttpServletResponse response){

        Student student = studentService.findStudentByUsername(username);

        if(student==null)
            return Msg.fail().add("msg","用户不存在");
        if(student.getStudentPassword().equals(password)){

            //获取登陆时间 添加登陆记录
            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String currentTime = df.format(new Date());
            Map<String,Object> record = new HashMap<>();
            record.put("username",student.getStudentUsername());
            record.put("role","student");
            record.put("logintime",currentTime);
            studentService.addLoginRecord(record);

            Cookie cookie1 = new Cookie("username",username);
            Cookie cookie2 = new Cookie("role","student");
            cookie1.setPath("/");
            cookie2.setPath("/");
            cookie1.setDomain("localhost");
            cookie2.setDomain("localhost");
            response.addCookie(cookie1);
            response.addCookie(cookie2);

            return Msg.success();

        }else {
            return Msg.fail().add("msg","密码错误");
        }
    }



    /**
     * 学号查重
     * @param username
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/findStudent",method = RequestMethod.POST)
    public Msg findStudent(@RequestParam(value = "username") String username){

        boolean flag = studentService.findStudent(username);

        return Msg.success().add("flag",flag);
    }


}
